<template>
  <div class="options-management">
    <v-card class="elevation-10 rounded-xl pa-2">
      <v-card-title class="d-flex align-center">
        <span>参数管理</span>
        <v-spacer></v-spacer>
        <div class="d-flex gap-2">
          <v-btn 
            v-if="$perms('system_options_insert')"
            color="primary" 
            @click="handleInsert"
          >
            <v-icon start>mdi-plus</v-icon>
            添加
          </v-btn>
          
          <v-btn 
            v-if="$perms('system_options_import')"
            color="warning" 
            @click="handleImportExcel"
          >
            <v-icon start>mdi-upload</v-icon>
            导入
          </v-btn>
          
          <v-btn 
            v-if="$perms('system_options_export')"
            color="warning" 
            @click="handleExportExcel"
          >
            <v-icon start>mdi-download</v-icon>
            导出
          </v-btn>
          
          <v-btn 
            v-if="$perms('system_options_delete')"
            :disabled="!selectRows.length"
            color="error" 
            @click="handleDelete"
          >
            <v-icon start>mdi-delete</v-icon>
            批量删除
          </v-btn>
        </div>
      </v-card-title>

      <v-card-text>
        <!-- 查询表单 -->
        <v-row class="mb-4">
          <v-col cols="12" md="4">
            <v-text-field
              v-model="queryForm.optionCode_EQ"
              label="参数编号"
              placeholder="请输入参数编号"
              clearable
              variant="outlined"
              density="compact"
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="4">
            <v-text-field
              v-model="queryForm.optionName_LIKE"
              label="参数名称"
              placeholder="请输入参数名称"
              clearable
              variant="outlined"
              density="compact"
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="4" class="d-flex align-center">
            <v-btn color="primary" @click="queryData">
              <v-icon start>mdi-magnify</v-icon>
              查询
            </v-btn>
          </v-col>
        </v-row>

        <!-- 数据表格 -->
        <v-data-table
          v-model="selectRows"
          v-model:page="queryForm.pageNo"
          v-model:items-per-page="queryForm.pageSize"
          :headers="headers"
          :items="list"
          :loading="listLoading"
          :items-length="total"
          :show-current-page="true"
          :show-select="true"
          class="elevation-10 rounded-lg"
          loading-text="正在加载..."
          no-data-text="暂无数据"
          @update:page="handlePageChange"
          @update:items-per-page="handleSizeChange"
        >
          <!-- 序号列 -->
          <template v-slot:item.index="{ index }">
            {{ (queryForm.pageNo - 1) * queryForm.pageSize + index + 1 }}
          </template>

          <!-- 操作列 -->
          <template v-slot:item.actions="{ item }">
            <div class="d-flex gap-2">
              <v-btn
                v-if="$perms('system_options_update')"
                size="small"
                variant="text"
                color="primary"
                @click="handleUpdate(item)"
              >
                编辑
              </v-btn>

              <v-btn
                v-if="$perms('system_options_delete')"
                size="small"
                variant="text"
                color="error"
                @click="handleDelete(item)"
              >
                删除
              </v-btn>
            </div>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 编辑对话框 -->
    <Edit ref="editRef" @fetchData="fetchData" />

    <!-- 导入对话框 -->
    <Import ref="importRef" @fetchData="fetchData" />
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { getList, doDelete, doDeleteAll, doExportExcel } from '@/api/system/options/SysOptionsManagement';
import { isNotNull } from '@/utils/validate';
import { useMessage } from '@/composables/useMessage';
import { useConfirm } from '@/composables/useConfirm';
import Edit from './components/SysOptionsManagementEdit.vue';
import Import from './components/SysOptionsManagementImport.vue';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError } = useMessage();
const { confirmDelete } = useConfirm();

// 响应式数据
const list = ref([]);
const listLoading = ref(true);
const total = ref(0);
const selectRows = ref([]);

// 查询表单
const queryForm = ref({
  pageNo: 1,
  pageSize: 10,
  optionCode_EQ: '',
  optionName_LIKE: ''
});

// 表格头部配置
const headers = ref([
  {
    title: '序号',
    key: 'index',
    align: 'center',
    sortable: false,
    width: '80px'
  },
  {
    title: '参数编号',
    key: 'optionCode',
    align: 'start',
    sortable: false,
    width: '200px'
  },
  {
    title: '参数名称',
    key: 'optionName',
    align: 'start',
    sortable: false,
    width: '200px'
  },
  {
    title: '参数值',
    key: 'optionValue',
    align: 'start',
    sortable: false
  },
  {
    title: '备注',
    key: 'remark',
    align: 'start',
    sortable: false
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    sortable: false,
    width: '160px'
  }
]);

// 组件引用
const editRef = ref();
const importRef = ref();

onMounted(() => {
  fetchData();
});

/**
 * 添加参数
 */
const handleInsert = () => {
  editRef.value?.showEdit();
};

/**
 * 编辑参数
 */
const handleUpdate = (row) => {
  if (row.id) {
    editRef.value?.showEdit(row);
  }
};

/**
 * 删除参数
 */
const handleDelete = async (row) => {
  if (row?.id) {
    // 单个删除
    try {
      const confirmed = await confirmDelete(`您确定要删除参数"${row.optionName}"吗？此操作不可撤销。`);
      
      if (confirmed) {
        const { msg } = await doDelete({ id: row.id });
        showSuccess(msg || '删除成功');
        await fetchData();
      }
    } catch (error) {
      console.error('删除失败:', error);
      showError('删除失败');
    }
  } else {
    // 批量删除
    if (selectRows.value.length > 0) {
      try {
        const confirmed = await confirmDelete(`您确定要删除选中的 ${selectRows.value.length} 个参数吗？此操作不可撤销。`);
        
        if (confirmed) {
          const ids = selectRows.value.map(item => item.id).join(',');
          const { msg } = await doDeleteAll({ ids });
          showSuccess(msg || '删除成功');
          selectRows.value = [];
          await fetchData();
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        showError('批量删除失败');
      }
    } else {
      showError('请先选择要删除的参数');
    }
  }
};

/**
 * 导出Excel
 */
const handleExportExcel = () => {
  try {
    doExportExcel(queryForm.value);
    showSuccess('导出任务已提交，请稍后下载');
  } catch (error) {
    console.error('导出失败:', error);
    showError('导出失败');
  }
};

/**
 * 导入Excel
 */
const handleImportExcel = () => {
  importRef.value?.show();
};

/**
 * 页面大小变更
 */
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size;
  queryForm.value.pageNo = 1;
  fetchData();
};

/**
 * 页码变更
 */
const handlePageChange = (page) => {
  queryForm.value.pageNo = page;
  fetchData();
};

/**
 * 查询数据
 */
const queryData = () => {
  queryForm.value.pageNo = 1;
  fetchData();
};

/**
 * 获取数据
 */
const fetchData = async () => {
  listLoading.value = true;
  try {
    const { data } = await getList(queryForm.value);
    if (isNotNull(data)) {
      list.value = data.rows || [];
      total.value = data.total || 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    showError('获取数据失败');
  } finally {
    setTimeout(() => {
      listLoading.value = false;
    }, 300);
  }
};
</script>

<style scoped>
.options-management {
  padding: 0;
}

.gap-2 {
  gap: 8px;
}
</style>
